<?php

namespace App\App\Services;

use App\Models\ActivityRecord\ActivityRecord;
use Illuminate\Support\Facades\Log;
use Validator;

use App\Support\Services\AlipaySDK\AopClient;
use App\Support\Services\AlipaySDK\AlipayFundTransToaccountTransferRequest;

/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2017/3/17
 * Time: 下午4:09
 */
class AlipayService
{
    /**
     * 微信
     */
    public function __construct()
    {
    }

    /**
     * 支付宝转账
     * @param string $id 活动中奖纪录id
     * @return Array
     */
    public function transferAccounts($id)
    {
        $valRes = Validator::make(['id' => $id], ['id' => 'string'], ['id.string' => '该活动没有这个中奖纪录！']);

        if ($valRes->fails()) {
            $msg = '该活动没有这个中奖纪录！';
            $logs['msg'] = $msg;
            Log::info($logs);

            $data['msg'] = $msg;
            return $data;
        }
        $logs = ['id' => $id, 'msg' => false, 'data' => false];

        $data = ['res' => false, 'msg' => '支付宝账号有误'];

        $res = ActivityRecord::find($id)->with('activity')->first();

        if (!$res) {
            $msg = '该活动中奖纪录不存在！';
            $logs['msg'] = $msg;
            Log::info($logs);

            $data['msg'] = $msg;

            return $data;
        }

        $logs['data'] = $res->toArray();

        $emailOrTel = $res->alipay;

        if (empty($emailOrTel)) {
            $msg = '该用户没有支付宝账号！';
            $logs['msg'] = $msg;
            Log::info($logs);

            $data['msg'] = $msg;
            return $data;
        }


        $data = ['emailOrTel' => $emailOrTel];

        if (is_numeric($emailOrTel)) {
            $rules = ['emailOrTel' => 'regex:/^1[3456789][0-9]{9}$/'];

            $message = [
                'emailOrTel.regex' => '手机号有误！'
            ];
        } else {
            $rules = ['emailOrTel' => 'required|email'];

            $message = [
                'emailOrTel.required' => '支付宝账号有误！',
                'emailOrTel.email' => '支付宝账号有误！'
            ];
        }

        $valRes = Validator::make($data, $rules, $message);

        if ($valRes->fails()) {
            $msg = '支付宝账号有误！';
            $logs['msg'] = $msg;
            Log::info($logs);

            $data = ['res' => false, 'msg' => $msg];
        } else {
            $res = $this->alipay($res->alipay, $res->name, $res->amount, $res->activity->name);

            if ($res) {
                $msg = '转账成功';
                $data = ['res' => true, 'msg' => $msg];
            } else {
                $msg = '转账失败';
                $data = ['res' => false, 'msg' => $msg];
            }

            $logs['msg'] = $msg;
            Log::info($logs);
        }

        return $data;
    }

    /**
     * @param String $alipay 收款方账户
     * @param String $payee_real_name 收款方真实姓名
     * @param double $amount 转账金额，单位：元。 只支持2位小数
     * @param String $activityName 活动名称
     * @return boolean
     */
    private function alipay($payee_account, $payee_real_name, $amount, $activityName)
    {

        //商户转账唯一订单号：发起转账来源方定义的转账单据号。请求时对应的参数，原样返回。
        $out_biz_no = 123456789;

        //支付宝分配给开发者的应用ID
        $appId = '2017030105978930';

        //请填写开发者私钥去头去尾去回车，一行字符串
        $rsaPrivateKey = 'MIICXgIBAAKBgQDI/Arbh/Zs5jUshHOVVpQUvjiLhCDOgYoz4d+Z0NtmnkyDdzeuhPcNc772p9C0ax5abLtpzULM/f8gWp6/jCTVvQn8GyeXE85Gh+IUo7lcirsJ5hPKZsafys16jfle9fA5nRZrJHq63aXMzgEtY0LqddBsLZ+SLqbZIaS2JcwMZwIDAQABAoGBAJgQYmKg5yiTsK2i9RSLcfSTy5J7gJrd1ePVROlK5YUpxfg9zipDvew2o8hZRgYLeeaul8nAHIeesVYYWj3Q2dhoesNhEm0CZUcfVE9w4f7IqsXHf2qHJLYC0goXh3EnN6WnJp8PRVe3KQlT2kNIoaT0ik4W+OKL3oMOH7VLQZbpAkEA+saGJ+WdgwpKc0pdHCKMqeHJM/6HH2vlJBBAhhTJEWUw/36qUMyI10eMFlxIvl3Dl5LzRZ++8PSC4qc8qY/xRQJBAM0r9yAo+INgdn+0P34Kbj7QmPQETtCXk+LJvJoBB4DIR/7tNnvRJJAOu2ccZE0ke0Opupd+vvu1vVb6W/Q3A7sCQQCZaiwWak1jJj+Hqn2twaEmKJ/rdBH78gjbeCnRHRQo1SwVkcrl5Urt0LJt14UVGM2Yg+jZtjGcvSj5OfBNl2a1AkA5WMaUOJ9tqTK18x2kDypNaGS4H9QfvZ5aT2Tl7s+4EUL+YDNQXF7J3TRIV8k5Pq8tdG1xFr4vANdRTl0RX6ctAkEA1dUrhiv7FJqTWYsP0fG4fvAWJbI84ZTPz4K1ltBLclmJWI+nSCAQu+1tlp/8n4r/L+qgkMzN0mlWqZVCURW4Bg==';

        //请填写支付宝公钥，一行字符串
        $alipayrsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';

        //付款方真实姓名
        $payer_real_name = '山东天下泉城传媒有限责任公司';

        //付款方显示姓名
        $payer_show_name = '山东天下泉城传媒有限责任公司';

        $remark = '';

        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $appId;
        $aop->rsaPrivateKey = $rsaPrivateKey;
        $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA'; //RSA2 | RSA
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new AlipayFundTransToaccountTransferRequest();
        $request->setBizContent("{" .
            "    \"out_biz_no\":\"" . $out_biz_no . "\"," .
            "    \"payee_type\":\"ALIPAY_LOGONID\"," .
            "    \"payee_account\":\"" . $payee_account . "\"," .
            "    \"amount\":\"" . $amount . "\"," .
            "    \"payer_real_name\":\"" . $payer_real_name . "\"," .
            "    \"payer_show_name\":\"" . $payer_show_name . "\"," .
            "    \"payee_real_name\":\"" . $payee_real_name . "\"," .
            "    \"remark\":\"" . $remark . "\"," .
            "    \"ext_param\":\"{\\\"order_title\\\":\\\"提现\\\"}\"" .
            "  }");
        $result = $aop->execute($request);

        //        dd($result);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            return true;
        } else {
            return false;
        }
    }

    public function getDirectPayUrl($orderInfo)
    {
        // 创建支付单。
        $alipay = app('alipay.web');
        $alipay->setOutTradeNo($orderInfo['order_id']);
        $alipay->setTotalFee($orderInfo['price'] * $orderInfo['number']);
        $alipay->setSubject($orderInfo['order_name']);
        $alipay->setBody($orderInfo['description']);
        $alipay->setQrPayMode('4'); //该设置为可选，添加该参数设置，支持二维码支付。
        return $alipay->getPayLink();
    }
}
